<template>
  <van-popup
    :show="show"
    position="bottom"
    round
    :style="{ height: '70%' }"
    @update:show="onUpdateShow"
  >
    <div class="todo-form-container">
      <van-nav-bar
        :title="isEditing ? 'Edit Todo' : 'Add Todo'"
        left-arrow
        @click-left="onClose"
      >
        <template #right>
          <van-button v-if="isEditing" type="danger" size="small" @click="onDelete">Delete</van-button>
        </template>
      </van-nav-bar>

      <van-form @submit="onSubmit" class="form-content">
        <van-cell-group inset>
          <van-field
            v-model="formData.title"
            name="title"
            label="Title"
            placeholder="What needs to be done?"
            :rules="[{ required: true, message: 'Title is required' }]"
          />

          <van-field
            v-model="formData.description"
            name="description"
            label="Description"
            type="textarea"
            rows="3"
            placeholder="Add details (optional)"
          />

          <van-field name="priority" label="Priority">
            <template #input>
              <van-radio-group v-model="formData.priority" direction="horizontal">
                <van-radio :name="1" checked-color="#ee0a24">High</van-radio>
                <van-radio :name="2" checked-color="#ff976a">Medium</van-radio>
                <van-radio :name="3" checked-color="#07c160">Low</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            readonly
            name="due_date"
            label="Due Date"
            :model-value="formattedDueDate"
            placeholder="Select due date (optional)"
            @click="showDatePicker = true"
          />

          <van-field name="completed" label="Status">
            <template #input>
              <van-switch v-model="formData.completed" size="20" />
            </template>
          </van-field>
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="isSubmitting">
            {{ isEditing ? 'Update' : 'Add' }} Todo
          </van-button>
        </div>
      </van-form>

      <van-popup v-model:show="showDatePicker" position="bottom" round>
        <van-date-picker
          title="Select Due Date"
          :min-date="minDate"
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
          :confirm-button-text="'确认'"
          :cancel-button-text="'取消'"
        />
      </van-popup>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { showToast, showDialog } from 'vant';
import { todoApi } from '../api';

const props = defineProps({
  visible: Boolean,
  todo: Object,
});

const emit = defineEmits(['update:visible', 'todo-added', 'todo-updated']);

// Form state
const show = ref(false);
const showDatePicker = ref(false);
const isSubmitting = ref(false);
const minDate = new Date();

// Form data
const formData = reactive({
  title: '',
  description: '',
  priority: 2, // Default: Medium
  due_date: null,
  completed: false
});

// Computed properties
const isEditing = computed(() => !!props.todo);

const formattedDueDate = computed(() => {
  if (!formData.due_date) return '';
  const date = new Date(formData.due_date);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
});

// Watch for visibility changes
watch(() => props.visible, (newVal) => {
  show.value = newVal;
  if (newVal && props.todo) {
    // Edit mode - populate form with todo data
    formData.title = props.todo.title;
    formData.description = props.todo.description || '';
    formData.priority = props.todo.priority;
    formData.due_date = props.todo.due_date;
    formData.completed = props.todo.completed;
  } else if (newVal) {
    // Add mode - reset form
    formData.title = '';
    formData.description = '';
    formData.priority = 2;
    formData.due_date = null;
    formData.completed = false;
  }
});

// Watch for popup close
watch(() => show.value, (newVal) => {
  if (!newVal) {
    emit('update:visible', false);
  }
});

// Methods
const onUpdateShow = (value) => {
  emit('update:visible', value);
};

const onClose = () => {
  show.value = false;
};

const onDateConfirm = (value) => {
  // 处理日期选择器的确认事件
  // 在新版本的Vant中，value可能是一个日期对象或者时间戳
  try {
    let date;
    if (typeof value === 'object' && value instanceof Date) {
      date = value;
    } else if (typeof value === 'number') {
      date = new Date(value);
    } else if (typeof value === 'string') {
      date = new Date(value);
    } else {
      console.error('Unexpected date format:', value);
      date = new Date();
    }

    formData.due_date = date.toISOString().split('T')[0];
    showDatePicker.value = false;
    console.log('Date selected:', formData.due_date);
  } catch (error) {
    console.error('Error processing date:', error);
    showToast('日期格式错误');
  }
};

const onSubmit = async () => {
  isSubmitting.value = true;

  try {
    if (isEditing.value) {
      // Update existing todo
      const response = await todoApi.updateTodo(props.todo.id, formData);
      emit('todo-updated', response);
      showToast('Todo updated successfully');
    } else {
      // Create new todo
      const response = await todoApi.createTodo(formData);
      emit('todo-added', response);
      showToast('Todo added successfully');
    }
    onClose();
  } catch (error) {
    showToast('Failed to save todo');
    console.error('Error saving todo:', error);
  } finally {
    isSubmitting.value = false;
  }
};

const onDelete = () => {
  showDialog({
    title: 'Delete Todo',
    message: 'Are you sure you want to delete this todo?',
    showCancelButton: true,
  }).then(async () => {
    try {
      await todoApi.deleteTodo(props.todo.id);
      emit('todo-updated', { id: props.todo.id, deleted: true });
      showToast('Todo deleted');
      onClose();
    } catch (error) {
      showToast('Failed to delete todo');
      console.error('Error deleting todo:', error);
    }
  });
};
</script>

<style scoped>
.todo-form-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.form-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}
</style>
